﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace Keyki.XNAGameEngine.Common.Console
{
	/// <summary>
	/// Console input history
	/// </summary>
	public class History : IEnumerable
	{
		private readonly List<string> m_history;
		private readonly int m_showCapacity;
		private int m_index;

		/// <summary>
		/// Make a new history object with capacity maxLength
		/// </summary>
		public History(int showCapacity)
		{
			m_history = new List<string>();
			m_showCapacity = showCapacity;
		}

		/// <summary>
		/// Returns the current command in history
		/// </summary>
		public string Current
		{
			get { return m_index < m_history.Count ? m_history[m_index] : ""; }
		}

		/// <summary>
		/// Gets the number of elements in history
		/// </summary>
		public int Count
		{
			get { return m_history.Count; }
		}

		#region IEnumerable Members

		public IEnumerator GetEnumerator()
		{
			return GetRange(m_index, m_showCapacity).GetEnumerator();
		}

		#endregion

		/// <summary>
		/// Add a command to the history
		/// </summary>
		/// <param name="str"></param>
		public void Add(string str)
		{
			string[] strings = str.Split('\n');

			foreach (string s in strings)
			{
				if (!String.IsNullOrWhiteSpace(s))
					m_history.Add(s);
			}

			m_index = m_history.Count;
		}

		/// <summary>
		/// Cycle backwards through commands in history
		/// </summary>
		/// <returns></returns>
		public string Previous()
		{
			if (m_index > 0)
			{
				m_index--;
			}
			return Current;
		}

		/// <summary>
		/// Cycle forwards through commands in history
		/// </summary>
		/// <returns></returns>
		public string Next()
		{
			if (m_index < m_history.Count - 1)
			{
				m_index++;
			}
			return Current;
		}

		/// <summary>
		/// Erase command history
		/// </summary>
		public void Clear()
		{
			m_history.Clear();
		}

		private List<String> GetRange(int start, int count)
		{
			if (m_history.Count > count)
			{
				if (start - count < 0)
					start += count - start; // in console always will be max allowed components

				return m_history.GetRange(start - count, count);
			}

			return m_history;
		}
	}
}